<!doctype html>
<title>llama.cpp chat</title>
<meta charset="utf-8"/>
<style>
body{font-family:Arial;background:#111;color:#eee;margin:0;padding:0}
#box{max-width:750px;margin:20px auto;}
#log{border:1px solid #444;height:60vh;overflow-y:auto;padding:10px}
input{width:97.5%;padding:8px;font-size:18px;background:#222;color:#eee;border:1px solid #555}
.user{color:#0ff}
.assistant{color:#ff0}
</style>
<div id="box">
  <div id="log"></div>
  <input id="in" placeholder="问点什么…" autocomplete="off"/>
</div>
<script>
const log=document.getElementById('log');
const inp=document.getElementById('in');
async function send(){
  const q=inp.value.trim(); if(!q)return;
  inp.value='';
  log.insertAdjacentHTML('beforeend',`<div class=user>你：${q}</div>`);
  log.insertAdjacentHTML('beforeend',`<div class=assistant>AI：</div>`);
  const target=log.lastElementChild;
  const res=await fetch('http://127.0.0.1:8080/completion',{
    method:'POST',
    headers:{'Content-Type':'application/json'},
    body:JSON.stringify({prompt:q,n_predict:256,stream:true})
  });
  const reader=res.body.pipeThrough(new TextDecoderStream()).getReader();
  while(true){
    const {value,done}=await reader.read();
    if(done)break;
    for(const line of value.split('\n')){
      if(line.startsWith('data: ')){
        const tok=JSON.parse(line.slice(6)).content;
        target.textContent+=tok;
      }
    }
  }
}
inp.addEventListener('keydown',e=>{if(e.key==='Enter')send()});
</script>
